package com.guo.hui.shiro;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.guo.hui.dao.shiro.TpPermissionMapper;
import com.guo.hui.dao.shiro.TpRoleMapper;
import com.guo.hui.dao.shiro.TpUserMapper;
import com.guo.hui.model.shiro.TpUser;
import com.guo.hui.service.TpUserShiroService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private TpUserMapper tpUserDao;
	@Autowired
	private TpRoleMapper tpRoleDao;
	@Autowired
	private TpPermissionMapper tpUpermissonDao;

	public ShiroRealm() {
		super();
	}

	/**
	 * Shiro 身份验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		ShiroToken token = (ShiroToken) authcToken;
		// 数据库查询权限
		TpUser user = tpUserDao.loginAuth(token.getUsername(), token.getPswd());
		if (user != null) {
			return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		}
		//
		return null;
	}

	/**
	 * Shiro权限验证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		TpUser user = (TpUser) principals.getPrimaryPrincipal();
		int uid = user.getId();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 根据用户ID查询角色(role),放入到Authorization里。
		Set<String> roles = tpRoleDao.selectByUserId(uid);
		info.setRoles(roles);
		// // 根据用户ID查询权限(permission),放入到Authorization里。
		Set<String> permissions = tpUpermissonDao.selectByUserId(uid);
		info.setStringPermissions(permissions);
		return info;
	}

}
